
import java.io.FileReader;

import java_cup.runtime.Scanner;
import symbolesPackage.TableDesSymboles;
import typage.Declarator;
import typage.Remplissor;
import typage.Typer;
import ast.JmmFile;
import errors.TypeError;

/* we extend the (CUP-generated) parser class to print nicer
 error messages */

class Main {
	
	static boolean parse_only = false, type_only = false;

	static void report(String filename, int line, int character) {
		System.out.println("File \"" + filename + "\"" + ", line " + line
				+ ", character " + character + ":");
	}

	static void usage() {
		System.out
				.println("usage: compilo [-parse-only] [-type-only] file.jmm");
		System.exit(1);
	}

	public static void main(String arg[]) {
		String filename = null;

		for (int i = 0; i < arg.length; i++) {
			String a = arg[i];
			if (a.equals("-parse-only"))
				parse_only = true;
			else if (a.equals("-type-only"))
				type_only = true;
			else {
				if (filename != null)
					usage();
				filename = a;
			}
		}

		if ( filename==null || !filename.endsWith(".jmm"))
			usage();

		try 
		{
			Scanner lex = new Lexer(new FileReader(filename));
			parser p = new Myparser(lex, filename);
			JmmFile ast = (JmmFile) p.parse().value;
			
			if (parse_only)	System.exit(0); 
			// (new Pretty()).visit(ast);
			
			
			TableDesSymboles tds = new TableDesSymboles();
			
			(new Declarator(tds)).visit(ast);
			
			(new Remplissor(tds)).visit(ast);
			
			
			(new Typer(tds)).visit(ast);
			
			if (type_only) System.exit(0);
			
			System.out.println("compilation ok");
			System.exit(0); 
			
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		} catch (TypeError e) {
			System.err.println(e.toString());
		}
	}
}
